package com.licheedev.demo.main;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bin.david.form.core.SmartTable;
import com.firefly.api.FireflyApi;
import com.firefly.api.serialport.SerialPort;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.licheedev.demo.App;
import com.licheedev.demo.ChooseModeActivity;
import com.licheedev.demo.MainActivity;
import com.licheedev.demo.R;
import com.licheedev.demo.base.ToastUtil;
import com.licheedev.demo.dao.CarInfoDao;
import com.licheedev.demo.dao.HistroyBeamDao;
import com.licheedev.demo.equip.SystemEquip;
import com.licheedev.demo.histroy.CarInfo;
import com.licheedev.demo.histroy.HistroyBeam;
import com.licheedev.demo.tablebean.TempShowBean;
import com.licheedev.demo.tcp.NioServer;
import com.licheedev.demo.tcp.TcpMsg;
import com.licheedev.demo.utils.SPUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.firefly.api.serialport.SerialPort;
import com.firefly.api.serialport.SerialPort.Callback;
import com.firefly.api.serialport.SerialPortFinder;
import com.licheedev.demo.utils.SerialCallBack;
import com.licheedev.demo.utils.SeriseUtils;
//导入TTS的包
//导入监听包

/*
DTU1  192.168.1.100 DTU2  192.168.1.101  Pingmu1  192.168.1.102 Pingmu2  192.168.1.103 Chepai1  192.168.1.104 Chepai2  192.168.1.105
 */
public class MainFunctionActivity extends AppCompatActivity implements OnInitListener {
    ArrayList<Integer> weightList = new ArrayList<>();
    HashSet<String> tempCarList = new HashSet<>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    ArrayList<HistroyBeam> tableList = new ArrayList<>();
    SystemEquip equip;  //系统状态
    Context context;
    @BindView(R.id.table)
    SmartTable table;
    NioServer server;
    @BindView(R.id.img_dtu1)
    ImageView imgDtu1; //DTU1
    @BindView(R.id.img_dtu2)
    ImageView imgDtu2; //DTU2
    @BindView(R.id.img_pinmu1)
    ImageView imgPinmu1; //屏幕1
    @BindView(R.id.img_pinmu2)
    ImageView imgPinmu2; //屏幕2
    @BindView(R.id.img_chepai1)
    ImageView imgChepai1; //车牌1
    @BindView(R.id.img_chepai2)
    ImageView imgChepai2; //车牌2
    @BindView(R.id.tv_CarNum)
    TextView tvCarNum;
    @BindView(R.id.tv_setMsg)
    TextView tvSetMsg;
    @BindView(R.id.tv_showMsg)
    TextView tvShowMsg;
    @BindView(R.id.tv_fahuo)
    TextView tvFahuo;
    @BindView(R.id.tv_shouhuo)
    TextView tvShouhuo;
    @BindView(R.id.tv_huowumingcheng)
    TextView tvHuowumingcheng;
    @BindView(R.id.tv_chexing)
    TextView tvChexing;
    @BindView(R.id.tv_yunshu)
    TextView tvYunshu;
    @BindView(R.id.tv_beizhu)
    TextView tvBeizhu;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_ic)
    TextView tvIc;
    @BindView(R.id.tv_chaozhong)
    TextView tvChaozhong;
    @BindView(R.id.tv_pizhong)
    TextView tvPizhong;
    @BindView(R.id.tv_maozhong)
    TextView tvMaozhong;
    @BindView(R.id.tv_jinzhong)
    TextView tvJinzhong;
    @BindView(R.id.tv_chaozai)
    TextView tvChaozai;
    @BindView(R.id.rb_way1_1)
    RadioButton rbWay11;
    @BindView(R.id.rb_way1_2)
    RadioButton rbWay12;
    @BindView(R.id.rb_way1_3)
    RadioButton rbWay13;
    @BindView(R.id.rb_way1_4)
    RadioButton rbWay14;
    @BindView(R.id.tv_num)
    TextView tvWeight;
    //定义一个tts对象
    private TextToSpeech tts;
    private String weight;
    private String Ip1, Ip2, Ip3, Ip4, Ip5, Ip6;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main_function);
        ButterKnife.bind(this);
        context = this;
        initView();
    }

    private void initView() {
        //初始化tts监听对象
        tts = new TextToSpeech(this, this);
        //设置 表格控件
        table.getConfig().setShowYSequence(false);
        table.getConfig().setShowXSequence(false);
        table.getConfig().setShowTableTitle(false);
        for(int i = 0 ;i<20;i++){
            weightList.add(0);
        }
        new Thread() {
            public void run() {
                try {
                    server = new NioServer();
                    server.bind(8000);
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
        }.start();
        LiveEventBus
                .get("frim_client", TcpMsg.class)
                .observe(this, new Observer<TcpMsg>() {
                    @Override
                    public void onChanged(@Nullable TcpMsg info) {
                        Log.d("TCP", "" + info.type);
                        switch (info.type) {
                            case 0: //连接
                                if (info.addr.equals(Ip1)) {
                                    imgDtu1.setBackground(context.getDrawable(R.color.colorPrimaryDark));
//                                    imgDtu1.setBackgroundResource();
                                }
                                if (info.addr.equals(Ip2)) {
                                    imgDtu2.setBackground(context.getDrawable(R.color.colorPrimaryDark));
                                }
                                if (info.addr.equals(Ip3)) {
                                    imgPinmu1.setBackground(context.getDrawable(R.color.colorPrimaryDark));
                                }
                                if (info.addr.equals(Ip4)) {
                                    imgPinmu2.setBackground(context.getDrawable(R.color.colorPrimaryDark));
                                }
                                if (info.addr.equals(Ip5)) {
                                    imgChepai1.setBackground(context.getDrawable(R.color.colorPrimaryDark));
                                }
                                if (info.addr.equals(Ip6)) {
                                    imgChepai2.setBackground(context.getDrawable(R.color.colorPrimaryDark));
                                }
                                break;

                            case 1: //断开
                                if (info.addr.equals(Ip1)) {
                                    imgDtu1.setBackgroundResource(R.color.hui);
                                }
                                if (info.addr.equals(Ip2)) {
                                    imgDtu2.setBackgroundResource(R.color.hui);
                                }
                                if (info.addr.equals(Ip3)) {
                                    imgPinmu1.setBackgroundResource(R.color.hui);
                                }
                                if (info.addr.equals(Ip4)) {
                                    imgPinmu2.setBackgroundResource(R.color.hui);
                                }
                                if (info.addr.equals(Ip5)) {
                                    imgChepai1.setBackgroundResource(R.color.hui);
                                }
                                if (info.addr.equals(Ip6)) {
                                    imgChepai2.setBackgroundResource(R.color.hui);
                                }
                                break;
                            case 2:
                                if (info.addr.equals(Ip1)) {     //DTU1

                                    String msg = info.msg;
                                    if (msg.startsWith("dtu1")) {
                                        equip.setNow(SystemEquip.Statue.WaitSave);
                                        rbWay13.setChecked(true);
                                        return;
                                    }

                                }
                                if (info.addr.equals(Ip2)) { //DTU2
                                    String msg = info.msg;  //保存数据
                                    if (msg.startsWith("dtu2")) {
                                        equip.setNow(SystemEquip.Statue.WaitStart);
                                        tvWeight.setText("###########");
                                        rbWay11.setChecked(true);
                                        return;
                                    }


                                }
                                if (info.addr.equals(Ip3)) { //显示器1
                                    String msg = info.msg;
                                    if (msg.startsWith("num")) {
                                        String[] arr = info.msg.split(",");
//                                        CarInfo carInfo = new CarInfo("冀A82339","张思","18933585857","河北钢铁","河北钢铁","河北钢铁","008253");
                                        CarInfo carInfo = new CarInfo(arr[1],arr[2],arr[3],arr[4],arr[5],arr[6],arr[7]);
                                        App.getmDaoSession().getCarInfoDao().insert(carInfo);
                                        return;
                                    }
                                }
                                if (info.addr.equals(Ip4)) { //显示器2
                                    String msg = info.msg;
                                    if (msg.startsWith("zhongliang")) {
                                        String[] arr = msg.split(",");
                                        tvWeight.setText(arr[1]);
                                        weight = arr[1];
                                        String carNum  =  tvCarNum.getText().toString();
                                        tts.speak(carNum+","+"本次称重"+weight+"吨。请下磅", TextToSpeech.QUEUE_FLUSH, null);

                                        HistroyBeam beam = null;
                                        if( tempCarList.contains(carNum) ){ //已经有车牌号了
                                            tempCarList.remove(carNum);

                                            List<HistroyBeam> list = App.getmDaoSession().getHistroyBeamDao().queryBuilder().
                                                    where(HistroyBeamDao.Properties.Carnum.eq(carNum)) .
                                                    orderAsc(HistroyBeamDao.Properties.Time).
                                                    limit(1).list();
                                            HistroyBeam histroyBeam = list.get(0);
                                            int x = Integer.parseInt(   histroyBeam.getWeight() );
                                            int y = Integer.parseInt( weight );
                                            beam = new HistroyBeam( new Date().getTime(),tvCarNum.getText().toString(),weight, 2,
                                                    tvName.getText().toString(),""+Math.min(x,y),""+Math.max(x,y),""+Math.abs(x-y),
                                                    tvYunshu.getText().toString(),tvFahuo.getText().toString(),tvShouhuo.getText().toString());
                                        }else {
                                            tempCarList.add(carNum);
                                            beam = new HistroyBeam( new Date().getTime(),tvCarNum.getText().toString(),weight, 1,
                                                    tvName.getText().toString(),"-","-","-",
                                                    tvYunshu.getText().toString(),tvFahuo.getText().toString(),tvShouhuo.getText().toString());
                                        }

                                        App.getmDaoSession().getHistroyBeamDao().insert(beam);

                                        List<HistroyBeam> list = App.getmDaoSession().getHistroyBeamDao().queryBuilder().orderDesc(HistroyBeamDao.Properties.Time).limit(10).list();
                                        table.setData(list);
                                        equip.setNow(SystemEquip.Statue.Waitgo);
                                        rbWay14.setChecked(true);
                                        return;
                                    }


                                }
                                if (info.addr.equals(Ip5)) { //车牌1

                                    String msg = info.msg;
                                    if (msg.startsWith("A")) {
                                        equip.setNow(SystemEquip.Statue.WaitWeight);
                                        rbWay12.setChecked(true);
                                        tvCarNum.setText(msg);
                                        tts.speak(msg+"。请上磅", TextToSpeech.QUEUE_FLUSH, null);
                                         //开启栏杆机
                                        List<CarInfo> infos = App.getmDaoSession().getCarInfoDao().queryBuilder().where(CarInfoDao.Properties.Carnum.eq(msg)).list();
                                        if (infos.size() != 0) {
                                            CarInfo res = infos.get(0);
                                            tvName.setText(res.getDriver());
                                            tvPhone.setText(res.getPhone());
                                            tvFahuo.setText(res.getFahuo());
                                            tvShouhuo.setText(res.getShouhuo());
                                            tvYunshu.setText(res.getYunshu());
                                            tvIc.setText(res.getIC());
                                        }
                                        return;
                                    }
//                                    tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null);


                                }
                                if (info.addr.equals(Ip6)) { //车牌2
//                                    tableList.add();
//                                    table.setData(tableList);
                                    String msg = info.msg;
                                    String[] strarr =  msg.split("\\+");
                                    for (int i =0 ;i <strarr.length;i++ ) {
                                        if(strarr[i].length() > 9){
                                            String temp = strarr[i].substring(0,6);


                                            if(i==1){
                                                tvWeight.setText(""+weightList.get(i) +"  公斤");
                                            }
                                            if(i==5){
                                                tvWeight.setText(""+weightList.get(i) +"  公斤");
                                            }
                                            if(i==7){
                                                tvWeight.setText(""+weightList.get(i) +"  公斤");
                                            }

                                            weightList.add(i,Integer.parseInt(temp));
                                        }
                                    }


                                }
                                break; //发送消息
                        }
                    }
                });
        //初始化 接入设备的IP
        Ip1 = (String) SPUtils.get(context, "IP1", "192.168.1.18");
        Ip2 = (String) SPUtils.get(context, "IP2", "192.168.1.18");
        Ip3 = (String) SPUtils.get(context, "IP3", "192.168.1.18");
        Ip4 = (String) SPUtils.get(context, "IP4", "192.168.1.18");
        Ip5 = (String) SPUtils.get(context, "IP5", "192.168.1.18");
        Ip6 = (String) SPUtils.get(context, "IP6", "192.168.1.18");
        equip = new SystemEquip();
    }

    private void setIp() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_layout, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).setTitle("外设IP设置").create();
        final EditText IP1 = view.findViewById(R.id.et_1);
        final EditText IP2 = view.findViewById(R.id.et_2);
        final EditText IP3 = view.findViewById(R.id.et_3);
        final EditText IP4 = view.findViewById(R.id.et_4);
        final EditText IP5 = view.findViewById(R.id.et_5);
        final EditText IP6 = view.findViewById(R.id.et_6);
        IP1.setText(Ip1);
        IP2.setText(Ip2);
        IP3.setText(Ip3);
        IP4.setText(Ip4);
        IP5.setText(Ip5);
        IP6.setText(Ip6);
        Button btnYes = view.findViewById(R.id.btn_yes);
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(IP1.getEditableText().toString())) {
                    SPUtils.put(context, "IP1", IP1.getEditableText().toString());
                    Ip1 = IP1.getEditableText().toString();
                }
                if (!TextUtils.isEmpty(IP2.getEditableText().toString())) {
                    SPUtils.put(context, "IP2", IP2.getEditableText().toString());
                    Ip2 = IP2.getEditableText().toString();
                }
                if (!TextUtils.isEmpty(IP3.getEditableText().toString())) {
                    SPUtils.put(context, "IP3", IP3.getEditableText().toString());
                    Ip3 = IP3.getEditableText().toString();
                }
                if (!TextUtils.isEmpty(IP4.getEditableText().toString())) {
                    SPUtils.put(context, "IP4", IP4.getEditableText().toString());
                    Ip4 = IP4.getEditableText().toString();
                }
                if (!TextUtils.isEmpty(IP5.getEditableText().toString())) {
                    SPUtils.put(context, "IP5", IP5.getEditableText().toString());
                    Ip5 = IP5.getEditableText().toString();
                }
                if (!TextUtils.isEmpty(IP6.getEditableText().toString())) {
                    SPUtils.put(context, "IP6", IP6.getEditableText().toString());
                    Ip6 = IP6.getEditableText().toString();
                }
                dialog.dismiss();
            }

        });
        dialog.show();
    }

    public void send(View view) {
        new Thread() {
            public void run() {
                try {

                    server.map.get("/192.168.5.14").channel().write("ggggggggggggggg");
                    server.map.get("/192.168.5.14").channel().flush();

                } catch (Exception e) {
                }
            }
        }.start();
    }

    /**
     * 显示 地磅历史
     */
    private void showHistroy(){
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_histroy_layout, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).setTitle("查找历史").create();
        SmartTable table = dialog.findViewById(R.id.table);
//        table.setData()
        dialog.show();
    }
    /**
     * 显示 地磅历史
     */
    private void showset(){
        final FireflyApi api = FireflyApi.create(context);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_layout, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();

        ImageView img1 = view.findViewById(R.id.img_1);
        img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean result = api.setEthIPAddress(false,null,null,null,null,null);
                if(result){
                    ToastUtil.show(context,"设置成功！");

                }else {
                    ToastUtil.show(context,"设置失败！");
                }
                dialog.dismiss();
            }
        });
        ImageView img2 = view.findViewById(R.id.img_2); //静态网络
        img2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showsetInter();
                dialog.dismiss();
            }
        });
        ImageView img3= view.findViewById(R.id.img_3); //关机
        img3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                api.shutDown(false);
            }
        });
        ImageView img4= view.findViewById(R.id.img_4); //重启
        img4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                api.reboot();
            }
        });
        ImageView img5 = view.findViewById(R.id.img_5);
        img5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, ChooseModeActivity.class));
                dialog.dismiss();
            }
        });
        ImageView img6 = view.findViewById(R.id.img_6); //设置时间
        img6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showsetTime();
                dialog.dismiss();
            }
        });
        ImageView img7 = view.findViewById(R.id.img_7); //设置时间
        img7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showsetSeri();
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 设置串口
     */
    private void showsetSeri() {
        final FireflyApi api = FireflyApi.create(context);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_serice, null, false);
        final EditText bot =   view.findViewById(R.id.et_1);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
        Button btnYes = view.findViewById(R.id.btn_yes);
        Button btnNo = view.findViewById(R.id.btn_no);
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

              String res =   bot.getEditableText().toString().trim();
              int botra = Integer.parseInt(res);
                SeriseUtils.openSerialPort("/dev/ttyS1", botra, new SerialCallBack() {
                    @Override
                    public void msgCome(String msg) {

                    }
                });
                ToastUtil.show(context,"开启串口成功");
                dialog.dismiss();
            }
        });
        btnNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SeriseUtils.closeSerialPort();
                ToastUtil.show(context,"关闭串口成功");
                dialog.dismiss();
            }
        });



        dialog.show();
    }

    /**
     * 设置时间
     */
    private void showsetTime(){
        final FireflyApi api = FireflyApi.create(context);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_time, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
        Button btnYes = view.findViewById(R.id.btn_yes);
        btnYes.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                String nian = (  (EditText)dialog.findViewById(R.id.et_1) ).getEditableText().toString().trim();
                String yue = (  (EditText)dialog.findViewById(R.id.et_2) ).getEditableText().toString().trim();
                String ri = (  (EditText)dialog.findViewById(R.id.et_3) ).getEditableText().toString().trim();
                String shi = (  (EditText)dialog.findViewById(R.id.et_4) ).getEditableText().toString().trim();
                String fen = (  (EditText)dialog.findViewById(R.id.et_5) ).getEditableText().toString().trim();
                String miao = (  (EditText)dialog.findViewById(R.id.et_6) ).getEditableText().toString().trim();
//                boolean result = api.setTime(Integer.parseInt(nian),
//                        Integer.parseInt(yue),
//                        Integer.parseInt(ri),
//                        Integer.parseInt(shi),
//                        Integer.parseInt(fen),
//                        Integer.parseInt(miao));
                boolean result = api.setTime(2020,
                        11,
                        24,
                        11,
                       25,
                       11);
                if(result){
                    ToastUtil.show(context,"设置成功！");
                    dialog.dismiss();
                }else {
                    ToastUtil.show(context,"设置失败！");
                    dialog.dismiss();
                }
            }
        });


        dialog.show();
    }
    /**
     * 设置网络
     */
    private void showsetInter(){
        final FireflyApi api = FireflyApi.create(context);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_set_ip, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
        Button btnYes = view.findViewById(R.id.btn_yes);
        btnYes.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                String ip = (  (EditText)dialog.findViewById(R.id.et_1) ).getEditableText().toString().trim();
                String mask = (  (EditText)dialog.findViewById(R.id.et_2) ).getEditableText().toString().trim();
                String gw = (  (EditText)dialog.findViewById(R.id.et_3) ).getEditableText().toString().trim();
                String dns1 = (  (EditText)dialog.findViewById(R.id.et_4) ).getEditableText().toString().trim();
                String dns2 = (  (EditText)dialog.findViewById(R.id.et_5) ).getEditableText().toString().trim();

//                boolean result = api.setTime(Integer.parseInt(nian),
//                        Integer.parseInt(yue),
//                        Integer.parseInt(ri),
//                        Integer.parseInt(shi),
//                        Integer.parseInt(fen),
//                        Integer.parseInt(miao));
                boolean result = api.setEthIPAddress(true,
                        ip,
                        mask,
                        gw,
                        dns1,
                        dns2);
                if(result){
                    ToastUtil.show(context,"设置成功！");
                    dialog.dismiss();
                }else {
                    ToastUtil.show(context,"设置失败！");
                    dialog.dismiss();
                }
            }
        });


        dialog.show();
    }
    @OnClick({R.id.tv_setMsg, R.id.tv_showMsg,R.id.tv_showHistroy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_setMsg:
                setIp();
                break;
            case R.id.tv_showMsg:
                showset();
                break;
            case R.id.tv_showHistroy:
                showHistroy();
                break;
        }
    }

    @Override
    public void onInit(int status) {
        // 判断是否转化成功
        if (status == TextToSpeech.SUCCESS) {
            //默认设定语言为中文，原生的android貌似不支持中文。
            int result = tts.setLanguage(Locale.CHINESE);
            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {

            } else {
                //不支持中文就将语言设置为英文
                tts.setLanguage(Locale.US);
            }
        }
    }
}